from ipaddress import IPv4Network, IPv4Address


def check_valid_subnet(subnet, parent_subnet=None, child_subnet_list=[]):
    """
    校验网段是否重叠
    :param subnet: 子网地址
    :param parent_subnet: 父级子网地址
    :param child_subnet_list: 子网列表
    :return:
    """
    check_subnet_net = int(IPv4Network(subnet).network_address)
    check_subnet_broadcast = int(IPv4Network(subnet).broadcast_address)
    if parent_subnet:
        parent_subnet_net = int(IPv4Network(parent_subnet).network_address)
        parent_subnet_broadcast = int(IPv4Network(parent_subnet).broadcast_address)
        if parent_subnet_net > check_subnet_net:
            return False
        if parent_subnet_broadcast < check_subnet_broadcast:
            return False
    for item in child_subnet_list:
        subnet_net = int(IPv4Network(item).network_address)
        subnet_broadcast = int(IPv4Network(item).broadcast_address)
        if parent_subnet:
            if subnet_net <= check_subnet_net <= subnet_broadcast:
                return False
            if subnet_net <= check_subnet_broadcast <= subnet_broadcast:
                return False
        else:
            if subnet_net <= check_subnet_net <= subnet_broadcast:
                return False
            if subnet_net <= check_subnet_broadcast <= subnet_broadcast:
                return False
            if check_subnet_net < subnet_net and check_subnet_broadcast > subnet_broadcast:
                return False
    return True


def get_network_address(subnet, data_type='str'):
    if data_type == 'str':
        return str(IPv4Network(subnet).network_address)
    return int(IPv4Network(subnet).network_address)


def get_broadcast_address(subnet, data_type='str'):
    if data_type == 'str':
        return str(IPv4Network(subnet).broadcast_address)
    return int(IPv4Network(subnet).broadcast_address)


def get_start_addrss(subnet):
    start_address = int(IPv4Network(subnet).network_address) + 1
    return str(IPv4Address(start_address))


def get_end_address(subnet):
    end_address = int(IPv4Network(subnet).broadcast_address) - 1
    return str(IPv4Address(end_address))


def get_net_mask(subnet):
    net_mask = IPv4Network(subnet).netmask
    return str(net_mask)


def get_gateway(subnet):
    net_address = int(IPv4Network(subnet).network_address)+1
    return str(IPv4Address(net_address))